# -*- coding: UTF-8 -*-


import os
import os.path
import sys
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(current_dir)
sys.path.append("..")

import case
import cash
import CaseCollection
from ruamel.yaml.comments import CommentedMap,CommentedSeq
from file_method import Time_cos
from collections import OrderedDict
         #10.18
import collections
# 小工程用例生成
# 命令1/命令2/ ...这样写
# @Time_cos.time_cost_caculate
def genCaseYaml(fileName, path, case_des_info,flag):
    # 获取信息模式  0 文件夹匹配 1 文件匹配
    cash_flag =int(flag)
    print("genSmallYAML begin!")
    assert os.path.exists(path)
    dirFilselist = []
    cashlist = []
    index = 0

    test_case = case.case()
    test_case = case_des_info
    # if(cash_flag==0):
    # # 规定表达式匹配格式  (文件夹匹配方式)
    #     value_pattern=re.compile(r'/value-([0-9]+)/')    #第一组
    #     currency_pattern=re.compile(r'/([A-Z]{3})/')   #第一组
    #     version_pattern=re.compile(r'/version-([0-9]{1,3}).*?/')   #第一组
    #     error_code_pattern=re.compile(r'/([0-9]{3})/')    #第一组
    #     CIS_pattern=re.compile(r'/(CIS_)(.*?)/')    #第二组
    #     direction_pattern=re.compile("/(direction-)([A-D])/")  #第二组
    #     #机型和冠字号匹配是个问题？  暂时先用读取位置代替
    #     factory_pattern=re.compile(r'/(CIS_.*?)/(.*?)/')   #第二组
    #     sn_pattern=re.compile(r'/version-.*?/(.*?)/direction-')   #第一组
    # else:
    # #  文件名匹配方式!
    # #20191108_111359_1_Model_JL_CNY_Err177_LastErr0x0_Den100_Dir0_Ver15_SN_BD14527154_cis_top.bmp
    #     value_pattern = re.compile(r'_Den(.*?)_')
    #     # currency_pattern = re.compile(r'/([A-Z]{3})/')
    #     currency_pattern = re.compile(r'_([A-Z]{3})_Err')
    #     version_pattern = re.compile(r'_Ver(.*?)_')
    #     error_code_pattern = re.compile(r'_Err(.*?)_')  # 第一组
    #     #CIS_pattern = re.compile(r'/(CIS_)(.*?)/')  # 第二组
    #     direction_pattern = re.compile("_Dir([A-D0-4]{1})_")  # 第二组
    #     # 机型和冠字号匹配是个问题？  暂时先用读取位置代替
    #     factory_pattern = re.compile(r'/(CIS_.*?)/(.*?)/')  # 第二组
    #     sn_pattern = re.compile(r'_SN_(.*?)_')  # 第一组
    #     break_pattern=re.compile(r'_LastErr0x(.*?)_')    #刹车相关 break?

    count_total=0
    for parent, dirnames, filenames in os.walk(path):
        #  wwm 10.24 读取文件夹信息
        if not filenames:
            continue
        # if not dirnames and cash_flag==0:
        #     # 文件夹匹配模式
        #     value_temp=value_pattern.search(parent)
        #     currency_temp = currency_pattern.search(parent)
        #     version_temp = version_pattern.search(parent)
        #     error_code_temp = error_code_pattern.search(parent)
        #     CIS_temp = CIS_pattern.search(parent)
        #     direction_temp = direction_pattern.search(parent)
        #     factory_temp=factory_pattern.search(parent)
        #     #12.30 文件夹匹配不需要冠字号
        #     # sn_temp = sn_pattern.search(parent)
        #     sn_temp=""
        #     test_case.setInformationAttribute(test_case.factory_str,factory_temp.group(2))
        #     # 没有匹配的相关值直接使其等于None
        #     temp_a=[currency_temp,version_temp,value_temp,sn_temp,error_code_temp]
        #     temp_list=[k.group(1) if k else None for k in temp_a]
        #     temp_list.append(False)
            #err号单独处理
            # 最后一个刹车后暂时用False代替
           ##############################################

        for filename in filenames:
            name, ext = os.path.splitext(filename)
            if ".raw" == ext and "adc0" in name:
                print(".", end=' ')
                #12.30文件夹匹配不需要冠字号
                # if(cash_flag==0):
                    # if(sn_temp==None):  #当按上面的匹配找不到文件夹中的冠字号时从文件名中找
                    #     #文件夹匹配模式需要额外从文件名读取冠字号信息
                    #     sn_pattern_temp = re.compile(r'_SN_(.*?)_')  # 第一组
                    #     sn_temp_temp = sn_pattern_temp.search(filename)
                    #     if temp_list[3]!=None:
                    #         temp_list[3]=sn_temp_temp.group(1)
                # if(cash_flag==1):
                #     #  文件匹配模式
                #     value_temp = value_pattern.search(filename)
                #     currency_temp = currency_pattern.search(parent)
                #     version_temp = version_pattern.search(filename)
                #     error_code_temp = error_code_pattern.search(filename)
                #     direction_temp = direction_pattern.search(filename)
                #     factory_temp = factory_pattern.search(parent)
                #     sn_temp = sn_pattern.search(filename)
                #     break_temp=break_pattern.match(filename)
                #     #设置information factory信息
                #     if factory_temp:
                #         test_case.setInformationAttribute(test_case.factory_str, factory_temp.group(2))
                #     # 没有匹配的相关值直接使其等于0
                #     temp_a = [currency_temp, version_temp, value_temp, sn_temp, error_code_temp,break_temp]
                #     temp_list = [k.group(1) if k else None for k in temp_a]
                #     #刹车单独处理
                #     temp_list[5]=(False if(temp_list[5]==None) else True)
                #
                # ##########################  是人民币的情况下 将version进行转换
                # if temp_list[0]=="CNY":
                #     temp_list[1]=version_conversion(temp_list[1],temp_list[2])
                # ##########################
                # templist = name.split("_")  # list
                # lastDashLength = len(templist[len(templist) - 1])  # 4
                # tempStr = name[0:len(name) - lastDashLength]
                # adc0File = os.path.join(parent, tempStr + "adc0.raw")
                # adc1File = os.path.join(parent, tempStr + "adc1.raw")
                # topCISFile = os.path.join(parent, tempStr + "cis_top.bmp")
                # bottomCISFile = os.path.join(parent, tempStr + "cis_bottom.bmp")
                #
                # if not os.path.isfile(adc0File):
                #     print("can't open file %s" % adc0File)
                #     continue
                # if not os.path.isfile(adc1File):
                #     print("can't open file %s" % adc1File)
                #     continue
                # if not os.path.isfile(topCISFile):
                #     print("can't open file %s" % topCISFile)
                #     continue
                # if not os.path.isfile(bottomCISFile):
                #     print("can't open file %s" % bottomCISFile)
                #     continue

                # need test 4 files
                # tempCash = cash.cash(index)
                #
                # tempCash.setFileAttribute(tempCash.adc_0_str, adc0File)
                # tempCash.setFileAttribute(tempCash.adc_1_str, adc1File)
                # tempCash.setFileAttribute(tempCash.cis_top_str, topCISFile)
                # tempCash.setFileAttribute(tempCash.cis_bottom_str, bottomCISFile)
                #
                # list(map(tempCash.setCashAttribute,tempCash.attribute_key,temp_list))
                # test_case.addCash(tempCash)

                index = index + 1
                count_total+=1
        #总数
        test_case.setDescriptionAttribute(test_case.total_sample_num_str,count_total)
        outfile = open(fileName, 'w',encoding="UTF-8")
        test_case.dumpToYaml(outfile)
        outfile.close()
# def genCollectionYaml(case_path, description=None, status=None, yaml_path=None, name=None):
#     print "genCollectionYaml begin!"
#     assert os.path.exists(case_path)
#     test_collaction=CaseCollection.CaseCollection()
#     if (name ==None):  #description  or yaml_path or
#         print "failed"
#         return False
#     # if (isinstance(name,str)):
#     for k, i in yaml_path.items():
#         # temp_dic={}
#         temp_dic=CommentedMap()      #for in order
#         temp_dic[test_collaction.name_str]=name[k]
#         temp_dic[test_collaction.description_str] = description[k]
#         temp_dic[test_collaction.status_str] = status[k]
#         temp_dic[test_collaction.path_str] = yaml_path[k]
#         test_collaction.addCase_info(temp_dic)
#         # print test_collaction.collection_dict
#         print k,"dic successs!"
#     test_collaction.dumpToYaml(case_path)
#     print "the task genCollectionYaml end!"


#是人民币的情况下将ver进行转换
def version_conversion(version_old,cash_value):
    if (version_old=="1"):
        return  "90"
    elif(version_old=="2"):
        return "99"
    elif(version_old=="3"):
        # return "05"
        return "5"
    elif(version_old=="4"):
        if(cash_value=="100"):
            return "15"
        if(cash_value=="50"):
            return "18"
    elif (version_old=="5"):
        if(cash_value=="100"):
            return "1512"
        if(cash_value == "1" or "10" or "20" or "50"):
            return "19"
    else:
        return version_old



#10.23 wwm
import re
@Time_cos.time_cost_caculate
def genCollectionYaml(case_path, description=None, status=None, file_path=None, name=None):
    print("genCollectionYaml begin!")
    test_collaction=CaseCollection.CaseCollection()
    # if (isinstance(name,str)):
    yaml_dic=[]
    # 匹配yaml文件
    file_pattern=re.compile(r'\.yaml$', re.I)
    for root, dirnames, filenames in os.walk(file_path):
        yaml_dic.append([os.path.join(root, filename) for filename in filenames if (file_pattern.findall(filename))])
    for k, i in enumerate(yaml_dic):
        # temp_dic={}
        for j,z in enumerate(yaml_dic[k]):
            temp_dic=CommentedMap()      #for in order
            temp_dic[test_collaction.name_str]=name
            temp_dic[test_collaction.description_str] = description
            temp_dic[test_collaction.status_str] = status
            temp_dic[test_collaction.path_str] = yaml_dic[k][j]
            test_collaction.addCase_info(temp_dic)
            # print test_collaction.collection_dict
            print("[%d][%d]set successs!" % (k, j))
    # 生成yaml
    test_collaction.dumpToYaml(case_path)
    print("the task genCollectionYaml end!")






